package com.government.web.controller.member;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.government.common.annotation.RepeatSubmit;
import com.government.common.constant.Constants;
import com.government.common.core.domain.entity.SysUser;
import com.government.common.core.domain.model.LoginUser;
import com.government.common.exception.ServiceException;
import com.government.common.utils.SecurityUtils;
import com.government.framework.web.service.TokenService;
import com.government.member.bo.BindParkBO;
import com.government.member.domain.BrowsingHistory;
import com.government.member.domain.UserHobby;
import com.government.member.service.BrowsingHistoryService;
import com.government.member.service.UserHobbyService;
import com.government.member.vo.AppletLoginVO;
import com.government.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.government.common.annotation.Log;
import com.government.common.core.controller.BaseController;
import com.government.common.core.domain.AjaxResult;
import com.government.common.enums.BusinessType;
import com.government.member.domain.MemberInfo;
import com.government.member.service.IMemberInfoService;
import com.government.common.utils.poi.ExcelUtil;
import com.government.common.core.page.TableDataInfo;

/**
 * 会员信息Controller
 *
 * @author system
 * @date 2023-09-18
 */
@RestController
@RequestMapping("/member/member")
public class MemberInfoController extends BaseController {
    @Autowired
    private IMemberInfoService memberInfoService;

    @Value(value = "${wx.appId}")
    private String appId;

    @Value(value = "${wx.secret}")
    private String secret;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private BrowsingHistoryService browsingHistoryService;

    @Autowired
    private UserHobbyService userHobbyService;


    /**
     * 查询会员信息列表
     */
    @PreAuthorize("@ss.hasPermi('member:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(MemberInfo memberInfo) {
        startPage();
        List<MemberInfo> list = memberInfoService.selectMemberInfoList(memberInfo);
        return getDataTable(list);
    }

    /**
     * 导出会员信息列表
     */
    @PreAuthorize("@ss.hasPermi('member:member:export')")
    @Log(title = "会员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MemberInfo memberInfo) {
        List<MemberInfo> list = memberInfoService.selectMemberInfoList(memberInfo);
        ExcelUtil<MemberInfo> util = new ExcelUtil<MemberInfo>(MemberInfo.class);
        util.exportExcel(response, list, "会员信息数据");
    }

    /**
     * 获取会员信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('member:member:query')")
    @GetMapping(value = "/{memberId}")
    public AjaxResult getInfo(@PathVariable("memberId") Long memberId) {
        return success(memberInfoService.selectMemberInfoByMemberId(memberId));
    }

    /**
     * 新增会员信息
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('member:member:add')")
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MemberInfo memberInfo) {
        return toAjax(memberInfoService.insertMemberInfo(memberInfo));
    }

    /**
     * 修改会员信息
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('member:member:edit')")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MemberInfo memberInfo) {
        return toAjax(memberInfoService.updateMemberInfo(memberInfo));
    }

    /**
     * 删除会员信息
     */
    @PreAuthorize("@ss.hasPermi('member:member:remove')")
    @Log(title = "会员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{memberId}")
    public AjaxResult remove(@PathVariable Long memberId) {
        return toAjax(memberInfoService.deleteMemberInfoByMemberId(memberId));
    }

    /**
     * 会员小程序登录
     */
    @PostMapping("/appletLogin")
    public AjaxResult appletLogin(String code) {
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        AppletLoginVO appletLoginVO = new AppletLoginVO();
        appletLoginVO.setSessionKey(String.valueOf(jsonObject.get("session_key")));
        String openId = String.valueOf(jsonObject.get("openid"));
        appletLoginVO.setOpenId(openId);

        return success(appletLoginVO);
    }

    /**
     * 小程序手机号验证
     */
    @PostMapping("/phoneValid")
    public AjaxResult phoneValid(String code, String openId) {
        // 获取access_token
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String accessToken = String.valueOf(jsonObject.get("access_token"));

        HashMap map = new HashMap();
        map.put("code", code);
        String wxUserInfoResult = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, JSONUtil.toJsonStr(map));
        JSONObject wxUserInfoObj = JSONUtil.parseObj(wxUserInfoResult);
        SysUser sysUser = null;
        if ("0".equals(String.valueOf(wxUserInfoObj.get("errcode")))) {
            JSONObject phoneInfoObj = (JSONObject) wxUserInfoObj.get("phone_info");
            String phoneNumber = String.valueOf(phoneInfoObj.get("phoneNumber"));

            sysUser = userService.selectUserByTel(phoneNumber);

            if (Objects.isNull(sysUser)) {
                // 用户信息
                sysUser = new SysUser();
                sysUser.setUserName(phoneNumber);
                sysUser.setPhonenumber(phoneNumber);
                sysUser.setNickName(phoneNumber);
                sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
                sysUser.setUserType("01");
                userService.registerUser(sysUser);

                // 会员信息
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.setMemberId(sysUser.getUserId());
                memberInfo.setUserName(phoneNumber);
                memberInfo.setMobPhone(phoneNumber);
                memberInfo.setTelephone(phoneNumber);
                memberInfo.setWechatOpenId(openId);
                memberInfo.setLastVist(new Date());
                memberInfo.setRegDate(new Date());
                memberInfoService.insertMemberInfo(memberInfo);
            }
        } else {
            ServiceException.throwExOnCondition(true, "登录失败");
        }
        AjaxResult ajax = AjaxResult.success();

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(sysUser.getUserId());
        loginUser.setUser(sysUser);
        String token = tokenService.createToken(loginUser);

        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 查询浏览记录
     */
    @GetMapping("/getBrowsingHistory")
    public TableDataInfo getBrowsingHistory() {

        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        startPage();
        List<BrowsingHistory> list = browsingHistoryService.getBrowsingHistoryByUserId(user.getUserId());
        return getDataTable(list);
    }

    /**
     * 清除浏览记录
     */
    @RepeatSubmit
    @PostMapping("/clearBrowsingHistory")
    public AjaxResult clearBrowsingHistory() {

        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        browsingHistoryService.clearBrowsingHistory(user.getUserId());
        return AjaxResult.success();
    }

    /**
     * 查询收藏记录
     */
    @GetMapping("/getCollectHistory")
    public AjaxResult getCollectHistory() {

        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        List<UserHobby> list = userHobbyService.getUserHobbyByUserId(user.getUserId());
        return AjaxResult.success(list);
    }

    /**
     * 绑定园区信息
     */
    @RepeatSubmit
    @PostMapping("/bindPark")
    public AjaxResult bindPark(@RequestBody BindParkBO bo) {

        memberInfoService.bindPark(bo.getParkAreaIds());
        return AjaxResult.success();
    }

}
